package com.lyubia.shop.order.interceptor;

import com.lyubia.shop.api.pojo.Admin;
import com.lyubia.shop.api.service.CookieService;
import com.lyubia.shop.api.service.SSOService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OrderLoginInterceptor implements HandlerInterceptor {

    @Resource
    private CookieService cookieService;

    @Value("${user.ticket}")
    private String userTicket;

    @Reference(version = "1.0")
    private SSOService ssoService;

    @Value("${shop.portal.url}")
    private String shopPortalUrl;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        try {
            String ticket = cookieService.getCookie(req);
            Admin admin = null;
            admin = ssoService.checkTicket(ticket);
            ssoService.freshTicket(ticket, admin);
            req.getSession().setAttribute("user",admin);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect(shopPortalUrl+"/toLogin?redirectUrl="+req.getRequestURL());
            return false;
        }
    }
}
